package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.dto.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R save(@RequestBody DishDto dishDto){
        //结束参数
        log.info("添加的商品为：{}",dishDto);
        //保存数据
        dishService.saveWithFlavor(dishDto);

        //清理缓存（全清理））清理指定的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        /*//清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/

        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);

        //构建分页
        Page<Dish> dishPage = new Page<>(page,pageSize);

        //构建条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null,Dish::getName,name);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //分页查询
        dishService.page(dishPage,lqw);

        //定义一个DishDto用来装数据
        //1. Page<DishDto>
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //分页基本数据: 当前页，总条数...
        //对象copy（本质getter/setter） 参数：源对象，目标对象，忽略的属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //records中的数据:
        List<Dish> records = dishPage.getRecords();

        List<DishDto> dishDtoList = records.stream().map(item -> {
            DishDto dishDto = new DishDto();
            //地上基本数据：name id image...
            BeanUtils.copyProperties(item, dishDto);
            //categoryName ? 通过cid去查询name
            Category category = categoryService.getById(item.getCategoryId());

            //拿到想要的分类
            //把分类放入dishDto类中
            dishDto.setCategoryName(category.getName());
            //手机成新的集合
            return dishDto;

        }).collect(Collectors.toList());

        //封装号这个数据集合放到Page<DishDto> records上
        dishDtoPage.setRecords(dishDtoList);
        //返回数据
        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        log.info("修改的信息:{}",dishDto);

        dishService.updateWithFlavor(dishDto);

        //清理某个分类下面的菜缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        /*//清理缓存（全清理））清理指定的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        return R.success("修改成功");
    }

    /**
     * 停售，起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R status(@PathVariable Integer status , @RequestParam List<Long> ids){
        log.info("ids为:{}",ids);
        log.info("status为:{}",status);

        dishService.statusWithDish(status,ids);

        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        dishService.deleteWithDish(ids);

        return R.success("数据删除成功");
    }

    /**
     * 根据条件查询菜品内容
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R listDish(Dish dish){
        log.info("菜品的分类为：{}",dish);

        //定义一个集合list
        List<DishDto> dishDtosList = new ArrayList<>();

        //定义一个key
        String key = "dish_" + dish.getCategoryId() + "_1";
        //从缓存中获取数据
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null){
            //数据赋值并返回
            dishDtosList = (List<DishDto>) o;
            return R.success(dishDtosList);
        }

        //构建查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //模糊查询
        lqw.like(dish.getName() != null,Dish::getName,dish.getName());
        //添加条件，查询状态为1（起售状态）的菜品
        lqw.eq(Dish::getStatus,1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);


        List<Dish> dishlist = dishService.list(lqw);

        //解决口味问题 list<DishDto>


        dishDtosList = dishlist.stream().map(item -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> flqw = new LambdaQueryWrapper<>();
            flqw.eq(dishDto.getId() != null, DishFlavor::getDishId, dishDto.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(flqw);

            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        //存入redis缓存（对象-->json）(jdk序列化器)
        redisTemplate.opsForValue().set(key,dishDtosList,10, TimeUnit.MINUTES);

        //返回数据
        return R.success(dishDtosList);
    }
}
